<template>
  <view class="data-source-switcher">
    <!-- 当前数据源状态 -->
    <view class="current-status">
      <view class="status-header">
        <text class="status-title">当前数据源</text>
        <view class="status-indicator" :class="statusClass">
          <text class="status-dot"></text>
          <text class="status-text">{{ statusText }}</text>
        </view>
      </view>
      
      <view class="current-source">
        <view class="source-icon">
          <uni-icons :type="currentConfig.icon" :color="currentConfig.color" size="24"></uni-icons>
        </view>
        <view class="source-info">
          <text class="source-name">{{ currentConfig.name }}</text>
          <text class="source-desc">{{ currentConfig.description }}</text>
        </view>
      </view>
    </view>

    <!-- 数据源选项 -->
    <view class="source-options">
      <text class="options-title">选择数据源</text>
      
      <view class="options-list">
        <view 
          v-for="source in availableSources" 
          :key="source.type"
          class="option-item"
          :class="{ active: source.isCurrent, disabled: !source.available }"
          @click="selectDataSource(source)"
        >
          <view class="option-icon">
            <uni-icons :type="source.icon" :color="source.color" size="20"></uni-icons>
          </view>
          
          <view class="option-content">
            <view class="option-header">
              <text class="option-name">{{ source.name }}</text>
              <view v-if="source.isCurrent" class="current-badge">
                <text class="badge-text">当前</text>
              </view>
              <view v-if="!source.available" class="unavailable-badge">
                <text class="badge-text">不可用</text>
              </view>
            </view>
            <text class="option-desc">{{ source.description }}</text>
            
            <!-- 特性标签 -->
            <view class="option-tags">
              <view v-if="source.requiresNetwork" class="tag network">
                <text class="tag-text">需要网络</text>
              </view>
              <view v-if="source.persistent" class="tag persistent">
                <text class="tag-text">数据持久化</text>
              </view>
              <view v-if="!source.requiresNetwork" class="tag offline">
                <text class="tag-text">离线可用</text>
              </view>
            </view>
          </view>
          
          <view class="option-action">
            <uni-icons 
              v-if="source.isCurrent" 
              type="checkmarkempty" 
              color="#2ecc71" 
              size="18"
            ></uni-icons>
            <uni-icons 
              v-else-if="source.available" 
              type="right" 
              color="#bdc3c7" 
              size="16"
            ></uni-icons>
          </view>
        </view>
      </view>
    </view>

    <!-- 高级选项 -->
    <view class="advanced-options">
      <text class="options-title">高级选项</text>
      
      <view class="advanced-list">
        <!-- 自动选择数据源 -->
        <view class="advanced-item" @click="autoSelectDataSource">
          <view class="advanced-icon">
            <uni-icons type="refresh" color="#3498db" size="20"></uni-icons>
          </view>
          <view class="advanced-content">
            <text class="advanced-name">自动选择</text>
            <text class="advanced-desc">根据网络状况自动选择最佳数据源</text>
          </view>
        </view>
        
        <!-- 数据同步 -->
        <view class="advanced-item" @click="showSyncDialog">
          <view class="advanced-icon">
            <uni-icons type="loop" color="#9b59b6" size="20"></uni-icons>
          </view>
          <view class="advanced-content">
            <text class="advanced-name">数据同步</text>
            <text class="advanced-desc">在不同数据源之间同步数据</text>
          </view>
        </view>
        
        <!-- 重置设置 -->
        <view class="advanced-item" @click="resetSettings">
          <view class="advanced-icon">
            <uni-icons type="trash" color="#e74c3c" size="20"></uni-icons>
          </view>
          <view class="advanced-content">
            <text class="advanced-name">重置设置</text>
            <text class="advanced-desc">恢复默认数据源设置</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 数据同步对话框 -->
    <uni-popup ref="syncPopup" type="dialog">
      <uni-popup-dialog 
        mode="base" 
        title="数据同步"
        content="选择同步方向和选项"
        :before-close="true"
        @close="closeSyncDialog"
      >
        <template v-slot:default>
          <view class="sync-dialog">
            <view class="sync-direction">
              <text class="sync-label">从</text>
              <picker 
                :value="syncFromIndex" 
                :range="syncSourceNames" 
                @change="onSyncFromChange"
              >
                <view class="sync-picker">
                  <text>{{ syncSourceNames[syncFromIndex] }}</text>
                  <uni-icons type="down" size="14"></uni-icons>
                </view>
              </picker>
              
              <text class="sync-label">到</text>
              <picker 
                :value="syncToIndex" 
                :range="syncSourceNames" 
                @change="onSyncToChange"
              >
                <view class="sync-picker">
                  <text>{{ syncSourceNames[syncToIndex] }}</text>
                  <uni-icons type="down" size="14"></uni-icons>
                </view>
              </picker>
            </view>
            
            <view class="sync-options">
              <label class="sync-option">
                <checkbox 
                  :checked="syncOptions.overwrite" 
                  @change="onSyncOptionChange('overwrite', $event)"
                />
                <text>覆盖现有数据</text>
              </label>
            </view>
            
            <view class="sync-actions">
              <button 
                class="sync-btn cancel" 
                @click="closeSyncDialog"
              >
                取消
              </button>
              <button 
                class="sync-btn confirm" 
                @click="startSync"
                :disabled="syncFromIndex === syncToIndex"
              >
                开始同步
              </button>
            </view>
          </view>
        </template>
      </uni-popup-dialog>
    </uni-popup>

    <!-- 同步进度对话框 -->
    <uni-popup ref="progressPopup" type="dialog">
      <uni-popup-dialog 
        mode="base" 
        title="同步进度"
        :before-close="false"
      >
        <template v-slot:default>
          <view class="progress-dialog">
            <view class="progress-info">
              <text class="progress-text">{{ syncProgress.text }}</text>
              <text class="progress-detail">{{ syncProgress.detail }}</text>
            </view>
            
            <view class="progress-bar">
              <view 
                class="progress-fill" 
                :style="{ width: syncProgress.percent + '%' }"
              ></view>
            </view>
            
            <view class="progress-stats">
              <text class="progress-stat">{{ syncProgress.percent }}%</text>
              <text class="progress-stat">{{ syncProgress.completed }}/{{ syncProgress.total }}</text>
            </view>
          </view>
        </template>
      </uni-popup-dialog>
    </uni-popup>
  </view>
</template>

<script>
import dataSourceManager, { DATA_SOURCE_TYPES } from '@/utils/dataSource'

export default {
  name: 'DataSourceSwitcher',
  data() {
    return {
      availableSources: [],
      currentConfig: {},
      statusText: '',
      statusClass: '',
      
      // 同步相关
      syncFromIndex: 0,
      syncToIndex: 1,
      syncSourceNames: [],
      syncOptions: {
        overwrite: false
      },
      syncProgress: {
        text: '',
        detail: '',
        percent: 0,
        completed: 0,
        total: 0
      }
    }
  },
  
  async mounted() {
    await this.loadDataSources()
    this.updateStatus()
    
    // 监听数据源变更
    dataSourceManager.addListener(this.onDataSourceChange)
  },
  
  beforeDestroy() {
    dataSourceManager.removeListener(this.onDataSourceChange)
  },
  
  methods: {
    /**
     * 加载可用数据源
     */
    async loadDataSources() {
      const sources = dataSourceManager.getAvailableDataSources()
      
      // 检查每个数据源的可用性
      for (const source of sources) {
        source.available = await dataSourceManager.checkDataSourceAvailability(source.type)
      }
      
      this.availableSources = sources
      this.syncSourceNames = sources.map(s => s.name)
      
      // 更新当前配置
      const currentSource = sources.find(s => s.isCurrent)
      if (currentSource) {
        this.currentConfig = currentSource
      }
    },
    
    /**
     * 更新状态显示
     */
    updateStatus() {
      const status = dataSourceManager.getStatus()
      
      if (status.isOnline) {
        this.statusText = '在线'
        this.statusClass = 'online'
      } else {
        this.statusText = '离线'
        this.statusClass = 'offline'
      }
    },
    
    /**
     * 选择数据源
     */
    async selectDataSource(source) {
      if (!source.available || source.isCurrent) {
        return
      }
      
      try {
        uni.showLoading({ title: '切换中...' })
        
        dataSourceManager.setDataSource(source.type)
        
        uni.hideLoading()
        uni.showToast({
          title: `已切换到${source.name}`,
          icon: 'success'
        })
        
        // 重新加载数据源状态
        await this.loadDataSources()
        this.updateStatus()
        
      } catch (error) {
        uni.hideLoading()
        uni.showToast({
          title: '切换失败: ' + error.message,
          icon: 'none'
        })
      }
    },
    
    /**
     * 自动选择数据源
     */
    async autoSelectDataSource() {
      try {
        uni.showLoading({ title: '检测中...' })
        
        const selectedSource = await dataSourceManager.autoSelectDataSource()
        
        uni.hideLoading()
        
        const sourceName = this.availableSources.find(s => s.type === selectedSource)?.name || selectedSource
        uni.showToast({
          title: `已自动选择: ${sourceName}`,
          icon: 'success'
        })
        
        await this.loadDataSources()
        this.updateStatus()
        
      } catch (error) {
        uni.hideLoading()
        uni.showToast({
          title: '自动选择失败: ' + error.message,
          icon: 'none'
        })
      }
    },
    
    /**
     * 显示同步对话框
     */
    showSyncDialog() {
      this.$refs.syncPopup.open()
    },
    
    /**
     * 关闭同步对话框
     */
    closeSyncDialog() {
      this.$refs.syncPopup.close()
    },
    
    /**
     * 同步源变更
     */
    onSyncFromChange(e) {
      this.syncFromIndex = e.detail.value
    },
    
    /**
     * 同步目标变更
     */
    onSyncToChange(e) {
      this.syncToIndex = e.detail.value
    },
    
    /**
     * 同步选项变更
     */
    onSyncOptionChange(key, e) {
      this.syncOptions[key] = e.detail.value
    },
    
    /**
     * 开始同步
     */
    async startSync() {
      if (this.syncFromIndex === this.syncToIndex) {
        uni.showToast({
          title: '源和目标不能相同',
          icon: 'none'
        })
        return
      }
      
      this.closeSyncDialog()
      this.$refs.progressPopup.open()
      
      const fromSource = this.availableSources[this.syncFromIndex].type
      const toSource = this.availableSources[this.syncToIndex].type
      
      try {
        const result = await dataSourceManager.syncData(fromSource, toSource, {
          overwrite: this.syncOptions.overwrite,
          onProgress: (progress) => {
            this.syncProgress = {
              text: `正在同步 ${progress.module}...`,
              detail: `${progress.completed}/${progress.total} 个模块`,
              percent: Math.round(progress.progress),
              completed: progress.completed,
              total: progress.total
            }
          }
        })
        
        setTimeout(() => {
          this.$refs.progressPopup.close()
          
          if (result.success) {
            uni.showToast({
              title: `同步完成: ${result.synced}个成功`,
              icon: 'success'
            })
          } else {
            uni.showToast({
              title: `同步失败: ${result.failed}个错误`,
              icon: 'none'
            })
          }
        }, 1000)
        
      } catch (error) {
        this.$refs.progressPopup.close()
        uni.showToast({
          title: '同步失败: ' + error.message,
          icon: 'none'
        })
      }
    },
    
    /**
     * 重置设置
     */
    resetSettings() {
      uni.showModal({
        title: '确认重置',
        content: '这将清除所有数据源设置，恢复为默认配置',
        success: (res) => {
          if (res.confirm) {
            dataSourceManager.reset()
            
            uni.showToast({
              title: '设置已重置',
              icon: 'success'
            })
            
            this.loadDataSources()
            this.updateStatus()
          }
        }
      })
    },
    
    /**
     * 数据源变更监听
     */
    onDataSourceChange(event) {
      console.log('[DataSourceSwitcher] 数据源变更:', event)
      this.loadDataSources()
      this.updateStatus()
    }
  }
}
</script>

<style lang="scss" scoped>
.data-source-switcher {
  padding: 20rpx;
  background-color: #f8f9fa;
  min-height: 100vh;
}

.current-status {
  background: white;
  border-radius: 16rpx;
  padding: 24rpx;
  margin-bottom: 24rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
}

.status-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.status-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #2c3e50;
}

.status-indicator {
  display: flex;
  align-items: center;
  gap: 8rpx;
  
  &.online {
    .status-dot {
      background-color: #2ecc71;
    }
    .status-text {
      color: #2ecc71;
    }
  }
  
  &.offline {
    .status-dot {
      background-color: #95a5a6;
    }
    .status-text {
      color: #95a5a6;
    }
  }
}

.status-dot {
  width: 12rpx;
  height: 12rpx;
  border-radius: 50%;
}

.status-text {
  font-size: 24rpx;
  font-weight: 500;
}

.current-source {
  display: flex;
  align-items: center;
  gap: 16rpx;
}

.source-icon {
  width: 48rpx;
  height: 48rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 12rpx;
  background-color: #f8f9fa;
}

.source-info {
  flex: 1;
}

.source-name {
  display: block;
  font-size: 28rpx;
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 4rpx;
}

.source-desc {
  font-size: 24rpx;
  color: #7f8c8d;
}

.source-options,
.advanced-options {
  background: white;
  border-radius: 16rpx;
  padding: 24rpx;
  margin-bottom: 24rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
}

.options-title {
  display: block;
  font-size: 32rpx;
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 20rpx;
}

.options-list,
.advanced-list {
  display: flex;
  flex-direction: column;
  gap: 16rpx;
}

.option-item,
.advanced-item {
  display: flex;
  align-items: center;
  gap: 16rpx;
  padding: 20rpx;
  border-radius: 12rpx;
  border: 2rpx solid #ecf0f1;
  transition: all 0.3s ease;
  
  &.active {
    border-color: #2ecc71;
    background-color: #f8fff9;
  }
  
  &.disabled {
    opacity: 0.5;
    pointer-events: none;
  }
  
  &:active {
    transform: scale(0.98);
  }
}

.option-icon,
.advanced-icon {
  width: 40rpx;
  height: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 8rpx;
  background-color: #f8f9fa;
}

.option-content,
.advanced-content {
  flex: 1;
}

.option-header {
  display: flex;
  align-items: center;
  gap: 12rpx;
  margin-bottom: 8rpx;
}

.option-name,
.advanced-name {
  font-size: 28rpx;
  font-weight: 600;
  color: #2c3e50;
}

.option-desc,
.advanced-desc {
  font-size: 24rpx;
  color: #7f8c8d;
  margin-bottom: 12rpx;
}

.current-badge,
.unavailable-badge {
  padding: 4rpx 12rpx;
  border-radius: 12rpx;
  font-size: 20rpx;
}

.current-badge {
  background-color: #2ecc71;
  
  .badge-text {
    color: white;
  }
}

.unavailable-badge {
  background-color: #e74c3c;
  
  .badge-text {
    color: white;
  }
}

.option-tags {
  display: flex;
  gap: 8rpx;
  flex-wrap: wrap;
}

.tag {
  padding: 4rpx 8rpx;
  border-radius: 8rpx;
  font-size: 20rpx;
  
  &.network {
    background-color: #e3f2fd;
    .tag-text {
      color: #1976d2;
    }
  }
  
  &.persistent {
    background-color: #f3e5f5;
    .tag-text {
      color: #7b1fa2;
    }
  }
  
  &.offline {
    background-color: #e8f5e8;
    .tag-text {
      color: #388e3c;
    }
  }
}

.option-action {
  width: 32rpx;
  height: 32rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 同步对话框样式 */
.sync-dialog {
  padding: 20rpx;
}

.sync-direction {
  display: flex;
  align-items: center;
  gap: 16rpx;
  margin-bottom: 24rpx;
}

.sync-label {
  font-size: 28rpx;
  color: #2c3e50;
}

.sync-picker {
  display: flex;
  align-items: center;
  gap: 8rpx;
  padding: 12rpx 16rpx;
  border: 2rpx solid #ecf0f1;
  border-radius: 8rpx;
  background-color: white;
  min-width: 120rpx;
}

.sync-options {
  margin-bottom: 24rpx;
}

.sync-option {
  display: flex;
  align-items: center;
  gap: 12rpx;
  font-size: 28rpx;
  color: #2c3e50;
}

.sync-actions {
  display: flex;
  gap: 16rpx;
  justify-content: flex-end;
}

.sync-btn {
  padding: 12rpx 24rpx;
  border-radius: 8rpx;
  font-size: 28rpx;
  border: none;
  
  &.cancel {
    background-color: #ecf0f1;
    color: #7f8c8d;
  }
  
  &.confirm {
    background-color: #3498db;
    color: white;
    
    &:disabled {
      background-color: #bdc3c7;
      color: #7f8c8d;
    }
  }
}

/* 进度对话框样式 */
.progress-dialog {
  padding: 20rpx;
  text-align: center;
}

.progress-info {
  margin-bottom: 24rpx;
}

.progress-text {
  display: block;
  font-size: 28rpx;
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 8rpx;
}

.progress-detail {
  font-size: 24rpx;
  color: #7f8c8d;
}

.progress-bar {
  width: 100%;
  height: 8rpx;
  background-color: #ecf0f1;
  border-radius: 4rpx;
  overflow: hidden;
  margin-bottom: 16rpx;
}

.progress-fill {
  height: 100%;
  background-color: #3498db;
  transition: width 0.3s ease;
}

.progress-stats {
  display: flex;
  justify-content: space-between;
  font-size: 24rpx;
  color: #7f8c8d;
}
</style>